<?PHP
function OpenTPL_function_sub( $string, $limit, $suffix = '', $charset = 'utf-8' ) {
    if( empty( $limit ) ) {
        return $string;
    }
    if( function_exists( 'mb_substr' ) ) {
        $substring = mb_substr( $string, 0, $limit, $charset );
    } else if( function_exists( 'iconv_substr' ) ) {
        $substring = iconv_substr( $string, 0, $limit, $charset );
    } else {
        $regex = array(
            'utf-8' => '/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/',
            'gb2312' => '/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/',
            'gbk' => '/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/',
            'big5' => '/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/'
        );
        preg_match_all( $regex[ strtolower( $charset ) ], $string, $match );
        $substring = join( '', array_slice( $match[ 0 ], 0, $limit ) );
    }

    if( strlen( $substring ) < strlen( $string ) ) {
        return $substring . $suffix;
    }
    return $substring;
}
?>